package org.erp.product.infrastructure.config;

import org.erp.product.infrastructure.enums.ConnectEventEnum;
import org.erp.product.infrastructure.enums.ConnectStatusEnum;

import java.util.HashMap;
import java.util.Map;

public class ConnectStateFlow {

    // 状态转移表
    private static final Map<ConnectStatusEnum, Map<ConnectEventEnum, ConnectStatusEnum>> FLOW = new HashMap<>();

    static {
        register(ConnectStatusEnum.WAITING_FOR_CONNECTION, ConnectEventEnum.CONNECTION, ConnectStatusEnum.CONNECTED);
        register(ConnectStatusEnum.WAITING_FOR_CONNECTION, ConnectEventEnum.OVERRULE, ConnectStatusEnum.IN_THE_REJECTION);
        register(ConnectStatusEnum.WAITING_FOR_CONNECTION, ConnectEventEnum.DIRECT_OVERRULE, ConnectStatusEnum.DISMISSED);
        register(ConnectStatusEnum.IN_THE_REJECTION, ConnectEventEnum.QUASH, ConnectStatusEnum.REVOKED);
        register(ConnectStatusEnum.IN_THE_REJECTION, ConnectEventEnum.CONFIRM_THE_REFUSAL, ConnectStatusEnum.DISMISSED);
    }

    private static void register(ConnectStatusEnum source, ConnectEventEnum event, ConnectStatusEnum target) {
        FLOW.computeIfAbsent(source, k -> new HashMap<>()).put(event, target);
    }

    public static ConnectStatusEnum next(ConnectStatusEnum current, ConnectEventEnum event) {
        Map<ConnectEventEnum, ConnectStatusEnum> eventMap = FLOW.get(current);
        if (eventMap == null) {
            throw new IllegalStateException("当前状态不允许任何流转: " + current);
        }
        ConnectStatusEnum next = eventMap.get(event);
        if (next == null) {
            throw new IllegalStateException("状态 " + current + " 不支持事件 " + event);
        }
        return next;
    }
}
